Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example 1:
Input: ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Note:
All given inputs are in lowercase letters a-z.
此題要求所有字串的前綴共通字串。
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if not strs: return ""
s_min = min(strs)
s_max = max(strs)
for i, ch in enumerate(s_min):
if ch != s_max[i]:
return s_min[:i]
return s_min
希望透過記錄解題的過程,可以對於資料結構及演算法等有更深一層的想法。
如有需訂正的地方歡迎告知,若有更好的解法也歡迎留言,謝謝。